use [family-annal]
GO
-- Drop trigger in table tb_fa_wife
IF OBJECT_ID ('tb_fa_wife.trigger_fa_wife_insert_update','TR') IS NOT NULL
   DROP TRIGGER tb_fa_wife.trigger_fa_wife_insert_update;
GO
-- Drop table and all constraint if exists
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[tb_fa_wife]') AND name = N'pk_tb_fa_wife')
BEGIN
ALTER TABLE [dbo].[tb_fa_wife] DROP CONSTRAINT [pk_tb_fa_wife]
END
GO
USE [family-annal]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_fa_wife]') AND type in (N'U'))
DROP TABLE [dbo].[tb_fa_wife]
GO
use [family-annal]
GO
-- create table wife
create table tb_fa_wife
(
	person_id int not null,
	wife_id int,
	first_name nvarchar(200),
	middle_name nvarchar(200),
	last_name nvarchar(200),
	birthday varchar(10), -- format date: dd/MM/yyyy
	death_day varchar(10), -- format date: dd/MM/yyyy
	number_children int, -- wife's children
	sex varchar(1) default 'Y', -- Y is male, N is female
	biography_id int, -- references to tb_fa_biography.biography_id
	born_id int, -- references to tb_fa_born.born_id
	create_date datetime,
	create_uid int,
	update_date datetime,
	update_uid int,
	person_status varchar(1) default 'Y'
);
GO
use [family-annal];
GO
-- create trigger for create_date
CREATE TRIGGER trigger_fa_wife_insert_update
   ON  tb_fa_wife 
   AFTER INSERT, UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF EXISTS(SELECT * FROM INSERTED)
    BEGIN
		update tb_fa_wife set create_date = GETDATE()
		from tb_fa_wife t join inserted i
		on t.wife_id = i.wife_id;
    END
    IF NOT EXISTS(SELECT * FROM UPDATED)
    BEGIN
		update tb_fa_wife set update_date = GETDATE()
		from tb_fa_wife t join updated u
		on t.wife_id = u.wife_id;
    END
END
GO